from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from common.views.base_views import BaseAPIView
from .models import *
from django.db.models import Max
import datetime, time
import uuid

def new_message(user_id):
    # 新消息
    new_message = False
    usermessage = UserUnreadMessage.objects.filter(user_id=user_id).first()
    if usermessage:
        unread_message_ids = usermessage.unread_message_ids

        if "WANT_BUY" in unread_message_ids:
            un_reads = unread_message_ids["WANT_BUY"]
            if un_reads:
                return True
        if "SYSTEM_MSG" in unread_message_ids:
            un_reads = unread_message_ids["SYSTEM_MSG"]
            if un_reads:
                return True
        if "GOT" in unread_message_ids:
            un_reads = unread_message_ids["GOT"]
            if un_reads:
                return True
        if "SOLD_OUT" in unread_message_ids:
            un_reads = unread_message_ids["SOLD_OUT"]
            if un_reads:
                return True
        if "PRE_SALE" in unread_message_ids:
            un_reads = unread_message_ids["PRE_SALE"]
            if un_reads:
                return True
        if "TAKE_OUT" in unread_message_ids:
            un_reads = unread_message_ids["TAKE_OUT"]
            if un_reads:
                return True
        if "GIFT" in unread_message_ids:
            un_reads = unread_message_ids["GIFT"]
            if un_reads:
                return True

    return new_message


class GetMessageListView(BaseAPIView):
    """
    获取消息列表
    """
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        user = request.user
        # user_id = 'c4a6da4644474054a7aa55a2d515662a'

        # msgs = Message.objects.values('msg_type').annotate(Max('add_timestamp'))

        try:
            offset = int(request.GET.get('offset', 0))
            limit = int(request.GET.get('limit', 15))
        except:
            offset = 0
            limit = 15



        resp = []
        # resp = {"WANT_BUY": {}, "SYSTEM_MSG": {}, "GOT": {}, "SOLD_OUT": {}, "PRE_SALE": {}, "TAKE_OUT": {}, "GIFT": {}}
        # resp["type"] = dict(Message.MsgType.get_choices()),
        usermessage, created = UserUnreadMessage.objects.get_or_create(user_id=user.id)
        if created:
            usermessage.last_message_id = {k: '' for k, v in Message.MsgType.get_choices()}
            usermessage.unread_message_ids = {k: [] for k, v in Message.MsgType.get_choices()}
        last_ids = usermessage.last_message_id
        unread_message_ids = usermessage.unread_message_ids
        for msg_type, v in Message.MsgType.get_choices():
            msg = None
            obj = {'category': msg_type, "isread": True, "unread": 0}
            msgid = last_ids.get(msg_type, '')
            if msgid:
                un_reads = unread_message_ids[msg_type]
                if msgid in un_reads:
                    obj['isread'] = False
                    obj['unread'] = len(un_reads).__str__()
                msg = Message.objects.filter(id=msgid).first()
            if msg:
                obj.update(msg.as_dict())
            resp.append(obj)
        resp.sort(key=lambda msg: msg.get('add_timestamp', 0), reverse=True)
        return Response(resp)


class ReadMessageView(BaseAPIView):
    """
    读信息
    """

    def post(self, request, *args, **kwargs):
        data = request.data
        id = data["id"]
        if not id:
            return Response({"code": "ok"})
        type = data["type"]

        user = request.user

        history_message = UserHistoryMessage.objects.filter(user_id=user.id, history_message_id=id,
                                                            msg_type=type).first()
        if history_message:
            history_message.isread = True
            history_message.save()
        else:
            UserHistoryMessage.objects.create(user_id=user.id, history_message_id=id, msg_type=type, isread=True)

        usermessage = UserUnreadMessage.objects.filter(user_id=user.id).first()
        if usermessage:
            unread_message_ids = usermessage.unread_message_ids
            ids = unread_message_ids[type]
            if id in ids:
                ids.remove(id)
                usermessage.save()

        # Message.objects.filter(id=id).first()

        return Response({"code": "ok"})


class CreateMessageView(BaseAPIView):

    @classmethod
    def message(cls, msg_type, product_name=None, oper_user=None, message_user_id=None, market_order_id=None,
                order_id=None, title=None, content=None, save=True):
        """
        消息详情
        WANT_BUY = "求Ta"
            SYSTEM_MSG = "系统消息"
            GOT = "已买入"
            SOLD_OUT = "已卖出"
            PRE_SALE = "产品预售"
            TAKE_OUT = "提仓"
            GIFT = "赠送"  #别人送给你
            GIFT_OVER = "赠送完成"
        :param msg_type:
        :param user_id:
        :param market_order_id:
        :return:
        """
        title = title
        content = content
        msg = Message(id=uuid.uuid4().hex)

        if not (title and content):
            if msg_type == Message.MsgType.WANT_BUY.name:  # "WANT_BUY":
                title = "用户%s想卖给你" % (oper_user.nickname)
                content = product_name + ",请点击查看详情"

            elif msg_type == Message.MsgType.GOT.name:  # "GOT":
                title = "成功买入: %s ，点击查看" % (product_name)
                content = title

            elif msg_type == Message.MsgType.SOLD_OUT.name:  # "SOLD_OUT":
                title = "已卖出: %s ，点击查看" % (product_name)
                content = title

            elif msg_type == Message.MsgType.PRE_SALE.name:  # "PRE_SALE":
                title = " %s 已经上线预售了！快来点击查看吧" % (product_name)
                content = title

            elif msg_type == Message.MsgType.TAKE_OUT.name:  # "TAKE_OUT":
                title = "您茶仓里的： %s 已提仓，快来点击查看吧" % (product_name)
                content = title

            elif msg_type == Message.MsgType.GIFT.name:  # "GIFT":
                title = "用戶 %s 赠送给你:" % (oper_user.nickname)
                content = product_name + ",请点击查看详情"

            elif msg_type == "GIFT_OVER":
                title = "您赠送给朋友 %s" % (oper_user.mobile)
                content = product_name + "已被接收,请点击查看详情"
                msg_type = Message.MsgType.GIFT.name  # "GIFT"

            elif msg_type == "RECEIVE":
                title = "收到%s的转账" % (oper_user.nickname)
                content = "接收转账,请点击查看详情"
                msg_type = Message.MsgType.RECEIVE.name  # "GIFT"
            elif msg_type == "TRANSFER":
                title = "转给%s" % (oper_user.nickname)
                content = "转账成功,请点击查看详情"
                msg_type = Message.MsgType.TRANSFER.name

        if oper_user:
            msg.from_user_id = oper_user.id
        msg.title = title
        msg.content = content
        msg.msg_type = msg_type
        msg.market_order_id = market_order_id
        msg.order_id = order_id
        msg.save()

        user_message = UserUnreadMessage.objects.filter(user_id=message_user_id).first()
        if user_message:
            if msg_type not in user_message.unread_message_ids:
                res = {msg_type: []}
                user_message.unread_message_ids.update(res)
            user_message.unread_message_ids[msg_type].append(msg.id)
            user_message.last_message_id[msg_type] = msg.id
        else:
            user_message = UserUnreadMessage(user_id=message_user_id)
            unread_message_ids = {msg_type: [msg.id]}
            last_message_id = {msg_type: msg.id}
            user_message.unread_message_ids = unread_message_ids
            user_message.last_message_id = last_message_id

        if save:
            user_message.save()
        return msg


class GetMessageWANTBUYView(BaseAPIView):
    """
    我的/消息通知/求Ta  type = WANT_BUY
    我的/消息通知/赠送  type = GIFT
    我的/消息通知/已买入  type = GOT
    我的/消息通知/已卖出  type = SOLD_OUT
    我的/消息通知/提仓  type = TAKE_OUT
    我的/消息通知/预售  type = PRE_SALE
    """

    def get(self, request, *args, **kwargs):
        user = request.user
        offset = request.GET.get('offset', 0)
        limit = request.GET.get('limit', 0)
        offset = int(offset)
        limit = int(limit)
        type = kwargs['type']
        type = type.upper()

        unusermessage = UserUnreadMessage.objects.filter(user_id=user.id).first()
        if unusermessage:
            unread_message_ids = unusermessage.unread_message_ids
            ids = ""
            if type in unread_message_ids:  # 'WANT_BUY'
                ids = unread_message_ids[type]

            for mid in ids:
                his_msg = UserHistoryMessage.objects.filter(user_id=user.id, history_message_id=mid, msg_type=type)
                if his_msg.count() == 0:
                    UserHistoryMessage.objects.create(user_id=user.id, history_message_id=mid, msg_type=type,
                                                      isread=False)

        try:
            offset = int(request.GET.get('offset', 0))
            limit = int(request.GET.get('limit', 15))
        except:
            offset = 0
            limit = 15

        count, message_list = UserHistoryMessage.objects.filter_by_page(offset=offset, limit=limit, user_id=user.id,
                                                                        msg_type=type)
        resp = {"count": count, "items": []}
        for message in message_list:
            msg = message.history_message

            item = msg.as_dict()
            item.update({'isread': message.isread})
            item.update({"is_effective": message.is_effective})

            resp['items'].append(item)

        # 预售 系统消息 点开列表为已读
        if type == Message.MsgType.PRE_SALE.name or type == Message.MsgType.SYSTEM_MSG.name:
            history_message = UserHistoryMessage.objects.filter(user_id=user.id, msg_type=type)
            for message in history_message:
                message.isread = True
                message.save()

            usermessage = UserUnreadMessage.objects.filter(user_id=user.id).first()
            if usermessage:
                unread_message_ids = usermessage.unread_message_ids
                unread_message_ids[type] = []
                usermessage.save()

        return Response(resp)
